<template>
  <VTable ref="tableRef" v-bind="tableOptions">
    <template #form="{ form }">
      <VGroup>
        <el-select v-model="form.input.type" style="width: 70px">
          <el-option label="SKU" value="sku"></el-option>
          <el-option label="SPU" value="spu"></el-option>
        </el-select>
        <VBatchInput v-model="form.input.value" placeholder="请输入" style="width: 200px" @search="query" />
      </VGroup>
      <VSelect v-model="form.product_level" placeholder="产品等级" :options="options.product_level || []" multiple collapse-tags style="min-width: 160px" />
      <el-input v-model="form.sku_cn_title" placeholder="产品名称" style="width: 200px"></el-input>
      <VSelect v-model="form.country" placeholder="国家" :options="options.country || []" multiple collapse-tags style="min-width: 160px" />
      <VSelect v-if="[2].includes(type)" v-model="form.warehouse_id" placeholder="仓库" :options="options.warehouse || []" multiple collapse-tags style="min-width: 160px" />
      <VCascader v-if="[3].includes(type)" v-model="form.sale_id" placeholder="运营人员" multiple collapse-tags style="min-width: 160px" />
      <VSelect v-model="form.is_replenishment" placeholder="是否需要备货" :options="options.is_replenishment || []" multiple collapse-tags style="min-width: 160px" />
      <VGroup>
        <div class="v-group-item">需求数量</div>
        <el-input-number v-model="form.replenishment_num.start" :controls="false" :min="0" :step="1" :precision="0" placeholder="最小值" class="w-24" />
        <div class="v-group-item">-</div>
        <el-input-number v-model="form.replenishment_num.end" :controls="false" :min="0" :step="1" :precision="0" placeholder="最大值" class="w-24" />
      </VGroup>
      <VCascader v-model="form.attribute_id" placeholder="产品分类" type="2" checkStrictly class="w-40" />
      <VBatchInput v-model="form.demand_no" placeholder="备库单号" style="width: 200px" @search="query" />
      <teleport v-if="load" :to="'#sku-filter' + type">
        <VSelect v-model="form.stock_out" placeholder="断货SKU筛选" :options="options.stock_out" multiple collapse-tags style="min-width: 140px" @change="query" />
      </teleport>
    </template>
    <template #high_form="{ form }">
      <div class="flex flex-wrap gap-3 vx-table__form-content">
        <VSelect v-model="form.sku_sales_status[0]" placeholder="商品状态" :options="options.sku_sale_status" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.supply_status[0]" placeholder="货源状态" :options="options.supply_status" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.activation[0]" placeholder="商品活跃度" :options="options.activation" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.is_demand[0]" placeholder="是否备料" :options="options.is_demand" multiple collapse-tags style="min-width: 160px" />
        <VCascader v-model="form.plan_user_id" placeholder="计划人员" multiple collapse-tags style="min-width: 160px" />
        <VCascader v-model="form.operate_user_id" placeholder="运营人员" multiple collapse-tags style="min-width: 160px" />
        <VCascader v-model="form.purchase_user_id" placeholder="采购人员" multiple collapse-tags style="min-width: 160px" />
        <VCascader v-model="form.develop_user_id" placeholder="开发人员" multiple collapse-tags style="min-width: 160px" />
        <VGroup>
          <div class="v-group-item">采购天数</div>
          <el-input-number v-model="form.purchase_day.start" placeholder="请输入" :controls="false" :min="0" :step="1" :precision="0" class="w-24" />
          <div class="v-group-item">-</div>
          <el-input-number v-model="form.purchase_day.end" placeholder="请输入" :controls="false" :min="0" :step="1" :precision="0" class="w-24" />
        </VGroup>
        <VGroup>
          <div class="v-group-item">运输天数</div>
          <el-input-number v-model="form.transit_day.start" placeholder="请输入" :controls="false" :min="0" :step="1" :precision="0" class="w-24" />
          <div class="v-group-item">-</div>
          <el-input-number v-model="form.transit_day.end" placeholder="请输入" :controls="false" :min="0" :step="1" :precision="0" class="w-24" />
        </VGroup>
        <VGroup>
          <div class="v-group-item">安全天数</div>
          <el-input-number v-model="form.safe_day.start" placeholder="请输入" :controls="false" :min="0" :step="1" :precision="0" class="w-24" />
          <div class="v-group-item">-</div>
          <el-input-number v-model="form.safe_day.end" placeholder="请输入" :controls="false" :min="0" :step="1" :precision="0" class="w-24" />
        </VGroup>
        <VGroup>
          <div class="v-group-item">可用库存</div>
          <el-input-number v-model="form.oversea_usable_num.start" placeholder="请输入" :controls="false" :min="0" :step="1" :precision="0" class="w-24" />
          <div class="v-group-item">-</div>
          <el-input-number v-model="form.oversea_usable_num.end" placeholder="请输入" :controls="false" :min="0" :step="1" :precision="0" class="w-24" />
        </VGroup>
        <VGroup>
          <div class="v-group-item">采购在途</div>
          <el-input-number v-model="form.purchase_transit_num.start" placeholder="请输入" :controls="false" :min="0" :step="1" :precision="0" class="w-24" />
          <div class="v-group-item">-</div>
          <el-input-number v-model="form.purchase_transit_num.end" placeholder="请输入" :controls="false" :min="0" :step="1" :precision="0" class="w-24" />
        </VGroup>
        <VGroup>
          <div class="v-group-item">头程在途</div>
          <el-input-number v-model="form.headway_transit_num.start" placeholder="请输入" :controls="false" :min="0" :step="1" :precision="0" class="w-24" />
          <div class="v-group-item">-</div>
          <el-input-number v-model="form.headway_transit_num.end" placeholder="请输入" :controls="false" :min="0" :step="1" :precision="0" class="w-24" />
        </VGroup>
        <VSelect v-model="form.header_channel_id" placeholder="运输类型" :options="options.header_channel_id" multiple collapse-tags style="min-width: 160px" />
        <VSelect v-model="form.supplier_name" placeholder="供应商" type="supplierName" allow-create multiple collapse-tags clearable filterable style="min-width: 180px" />
        <VSelect v-model="form.is_plan" placeholder="需要备料" :options="options.is_plan" multiple collapse-tags style="min-width: 160px" />
        <VGroup>
          <div class="v-group-item">一周销量</div>
          <el-input-number v-model="form.sale_week_num.start" placeholder="请输入" :controls="false" :min="0" :step="1" :precision="0" class="w-24" />
          <div class="v-group-item">-</div>
          <el-input-number v-model="form.sale_week_num.end" placeholder="请输入" :controls="false" :min="0" :step="1" :precision="0" class="w-24" />
        </VGroup>
        <VGroup>
          <div class="v-group-item">两周销量</div>
          <el-input-number v-model="form.sale_weeks_num.start" placeholder="请输入" :controls="false" :min="0" :step="1" :precision="0" class="w-24" />
          <div class="v-group-item">-</div>
          <el-input-number v-model="form.sale_weeks_num.end" placeholder="请输入" :controls="false" :min="0" :step="1" :precision="0" class="w-24" />
        </VGroup>
        <VCascader v-model="form.attribute_id" placeholder="产品分类" type="2" checkStrictly class="w-40" />
        <VSelect v-model="form.confirm_status" placeholder="需求数是否确认" :options="options.confirm_status" multiple collapse-tags style="min-width: 160px" />
        <VGroup>
          <div class="v-group-item">产品添加时间</div>
          <VDate v-model="form.dateRange.value" />
        </VGroup>
      </div>
    </template>
    <template #toolbar_btns>
      <VButton v-if="!sale" :auth="`/purchase/demand/${authPath}/add/${type}`" type="primary" :loading="loadings.createPlan" @click="handleBatch('createPlan')">创建备货计划</VButton>
      <VButton :auth="`/purchase/demand/${authPath}/updateSingle/${type}`" type="primary" :loading="loadings.updateSingle" @click="handleBatch('updateSingle')">手动更新（单条）</VButton>
      <VButton :auth="`/purchase/demand/${authPath}/update/${type}`" type="primary" :loading="loadings.update" @click="handleBatch('update')">手动更新（全量）</VButton>
      <VButton v-if="!sale" :auth="`/purchase/demand/${authPath}/confirm/${type}`" :loading="loadings.confirm" @click="handleBatch('confirm')">批量确认</VButton>
      <el-dropdown trigger="click" placement="bottom-start" @command="handleBatch">
        <VButton> 批量操作<i class="dk-iconfont icon-ArrowDown" /> </VButton>
        <template #dropdown>
          <el-dropdown-menu v-matomo>
            <el-dropdown-item command="updateRule">备货参数设置</el-dropdown-item>
            <el-dropdown-item command="saleRule">估算日销量规则设置</el-dropdown-item>
            <el-dropdown-item command="saleRatio">预估销量系数设置</el-dropdown-item>
            <el-dropdown-item command="activation">活跃状态设置</el-dropdown-item>
            <el-dropdown-item command="replenishment">备货状态设置</el-dropdown-item>
            <el-dropdown-item command="setPlan">计划人员配置</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
      <div :id="'sku-filter' + type" class="ml-auto"></div>
      <VExport mainKey="is_id" :name="exportList[type]" :tableRef="tableRef" task />
      <VButton :loading="loadings.exportSale" @click="() => exportSaleRef.open()">导出销量</VButton>
      <VExport v-if="!sale" mainKey="is_id" :name="['', 'sale-report', 'sale-report-warehouse', 'sale-report-sale'][type]" :tableRef="tableRef" task>导出14天销量</VExport>
      <VButton v-if="!sale" :loading="loadings.change1" @click="() => planRef.open()">计划人员分配</VButton>
      <div></div>
    </template>
  </VTable>
  <Add ref="addRef" :options="options" @success="query" />
  <SaleRatio ref="saleRatioRef" :options="options" @success="query" />
  <SaleRule ref="saleRuleRef" :options="options" @success="query" />
  <UpdateRule ref="updateRuleRef" :options="options" @success="query" />
  <Activation ref="activationRef" :options="options" @success="query" />
  <Replenishment ref="replenishmentRef" :options="options" @success="query" />
  <Plan ref="planRef" :options="options" @success="query" />
  <SetPlan ref="setPlanRef" :options="options" @success="query" />
  <DaySale ref="daySaleRef" />
  <Sale ref="saleRef" />
  <VLog ref="logRef" />
  <VHistory ref="historyRef" />
  <Chart ref="chartRef" :options="options" @success="query" />
  <Dialog ref="dialogRef" :sale="sale" :options="options" />
  <PurchaseOrder ref="purchaseOrderRef" />
  <ExportSale ref="exportSaleRef" :tableRef="tableRef" />
  <el-tooltip ref="tipRef" :visible="tip.visible" :virtual-ref="tip.ref" virtual-triggering placement="left" popper-class="demand-intelligent-tip" :offset="3" effect="light">
    <template #content>
      <div class="text-[16px] font-bold mt-3 mb-2">SKU+国家销量</div>
      <div class="grid grid-cols-10 border-l border-t base-border">
        <div v-for="(d, i) in saleData" :key="i" class="{'border-t': i < 10}">
          <div class="border-b border-r p-1 text-center text-[#333] dark:text-[#eee]">{{ d.date }}</div>
          <div class="border-b border-r p-1 text-center" :class="d.quantity ? 'text-[#0A14FF]' : 'text-[#333] dark:text-[#eee]'">{{ d.quantity }}</div>
        </div>
      </div>
    </template>
  </el-tooltip>
</template>

<script setup lang="jsx">
import Add from "./Add"
import UpdateRule from "./UpdateRule"
import SaleRatio from "./SaleRatio"
import SaleRule from "./SaleRule"
import DaySale from "./DaySale"
import Sale from "./Sale"
import Dialog from "./Dialog"
import Activation from "./Activation"
import Replenishment from "./Replenishment"
import Plan from "./Plan"
import SetPlan from "./SetPlan"
import ExportSale from "./ExportSale"
import PurchaseOrder from "./PurchaseOrder"
import Chart from "@/views/plan/sale/components/Chart"
import VHistory from "@/components/VHistory"
import { getOptionPms } from "@/api/public"
import { ElMessage, ElMessageBox } from "element-plus"
import { to } from "@/utils/action"
import { resMessage, resSkip } from "@/utils/res"
import { on, off } from "@/utils/dom"
import XEUtils from "xe-utils"

const props = defineProps({
  type: { type: [String, Number], default: "" },
  sale: Boolean,
})

const authPath = props.sale ? "intelligent-sale" : "intelligent"
const exportList = props.sale
  ? ["", "list_intelligent_stock", "list-intelligent-stock-warehouse", "list-intelligent-stock-sale"]
  : ["", "intelligent_stock", "intelligent-stock-warehouse", "intelligent-stock-sale"]
const api = inject("api")
const baseName = "intelligent_stock"
const tableRef = ref()
const logRef = ref()
const exportSaleRef = ref()
const purchaseOrderRef = ref()
const loadings = reactive({})
const { type } = props

provide("type", type)
// 查询
const query = () => {
  tableRef?.value.query()
}

// 获取options
const options = ref({})
getOptionPms({ type: baseName }).then((res) => {
  options.value = res.data
})

const load = ref(false)
nextTick(() => {
  load.value = true
})

const addRef = ref()

// 批量操作
const updateRuleRef = ref()
const saleRuleRef = ref()
const saleRatioRef = ref()
const activationRef = ref()
const replenishmentRef = ref()
const planRef = ref()
const setPlanRef = ref()
const handleBatch = (name) => {
  console.log("name", name)
  const selection = tableRef.value.$table.getCheckboxRecords()
  if (!selection.length && name !== "update") {
    ElMessage.warning("请先选择行")
    return
  }
  const is_ids = selection.map((d) => d.is_id)
  const showLoading = () => (loadings[name] = true)
  const closeLoading = () => (loadings[name] = false)
  const handle = {
    createPlan: () => {
      showLoading()
      api
        .createPlan({ is_ids, type })
        .then((res) => {
          resMessage({
            res,
            success: () => {
              ElMessage.success("操作成功")
              query()
            },
          })
        })
        .finally(closeLoading)
    },
    update: () => {
      showLoading()
      api
        .update()
        .then((res) => {
          ElMessage({ type: "success", message: "操作成功!" })
          query()
        })
        .finally(closeLoading)
    },
    updateSingle: () => {
      showLoading()
      api
        .updateSingle({ is_ids, type })
        .then((res) => {
          ElMessage({ type: "success", message: "操作成功!" })
          query()
        })
        .finally(closeLoading)
    },
    confirm: () => {
      showLoading()
      api
        .confirm({ is_ids, type })
        .then((res) => {
          ElMessage({ type: "success", message: "操作成功!" })
          query()
        })
        .finally(closeLoading)
    },
    updateRule: () => {
      updateRuleRef?.value.open(selection)
    },
    saleRule: () => {
      saleRuleRef?.value.open(selection)
    },
    saleRatio: () => {
      saleRatioRef?.value.open(selection)
    },
    activation: () => {
      activationRef?.value.open(selection)
    },
    replenishment: () => {
      replenishmentRef?.value.open(selection)
    },
    setPlan: () => {
      setPlanRef?.value.open(is_ids)
    },
    stop: () => {
      showLoading()
      api
        .change({ is_ids, status: 2, type })
        .then((res) => {
          ElMessage({ type: "success", message: "操作成功!" })
          query()
        })
        .finally(closeLoading)
    },
  }
  handle[name]()
}
// 单行操作
const daySaleRef = ref()
const historyRef = ref()
const saleRef = ref()
const handleRow = (name, row, rowIndex) => {
  const { is_id, status, sku } = row
  const showLoading = () => {
    loadings[name + rowIndex] = true
  }
  const closeLoading = () => {
    loadings[name + rowIndex] = false
  }
  const handle = {
    sale: () => {
      saleRef?.value.open(row)
    },
    daySale: () => {
      daySaleRef?.value.open(is_id)
    },
    change: () => {
      showLoading()
      api
        .change({ is_ids: [is_id], status: status === 1 ? 2 : 1, type })
        .then((res) => {
          query()
          ElMessage({ type: "success", message: "操作成功!" })
        })
        .finally(closeLoading)
    },
    log: () => {
      logRef?.value.open({ log_type: baseName, is_id })
    },
    history: () => {
      historyRef?.value.open(sku)
    },
    sku: () => {
      api.getGoodsSku({ sku: [row.sku], type }).then((res) => {
        to({
          path: "/goods/task/product/edit",
          query: {
            type: "view",
            spuId: res.data?.[0].spu_id,
            sku: row.custom_sku,
          },
        })
      })
    },
    planSale: () => {
      showLoading()
      api
        .planSale({ type, is_id, plan_estimate_day_sale_num: row.plan_estimate_day_sale_num })
        .then((res) => {
          query()
          ElMessage({ type: "success", message: "操作成功!" })
        })
        .finally(closeLoading)
    },
    replenishment: (ags) => {
      const closeMessage = () => ElMessageBox.close()
      const cancel = () => {
        closeMessage()
        query()
      }
      closeMessage()
      showLoading()
      api
        .replenishment({ type, is_id, replenishment_num: row.replenishment_num, ...ags })
        .then((res) => {
          const {
            data: { error_type },
            message,
          } = res
          resSkip({
            res,
            closeLoading,
            success: () => {
              query()
            },
            props: {
              customClass: "message-box-520",
              showCancelButton: false,
              showConfirmButton: false,
              message: () => (
                <div>
                  <div class="mb-2">{message}</div>
                  <div class="flex">
                    <el-button type="primary" class="ml-auto" onClick={() => handle["replenishment"]({ update_type: 1, error_type })}>
                      按整箱数
                    </el-button>
                    <el-button type="primary" onClick={() => handle["replenishment"]({ update_type: 2, error_type })}>
                      按填写值
                    </el-button>
                    <el-button onClick={cancel}>取消</el-button>
                  </div>
                </div>
              ),
            },
          })
        })
        .finally(closeLoading)
    },
  }
  handle[name]()
}

// 溢出处理

const tipRef = ref()
const tip = ref({
  visible: false,
  content: "",
  ref: null,
})
const saleData = ref([])
const updateTip = (val) => {
  tip.value = val
}
const handleMouseenter = async (row, { target }) => {
  const { sku, country, warehouse_id, sale_id } = row
  const end = XEUtils.toDateString(new Date(), "yyyy-MM-dd")
  const start = XEUtils.toDateString(XEUtils.getWhatDay(end, -30), "yyyy-MM-dd")
  const res = await api.getSale({ sku, country, payment_time: { start, end }, type, warehouse_id, sale_id })
  const { country_sale } = res.data
  saleData.value = country_sale
  updateTip({
    visible: true,
    ref: target,
  })
}
const closeTip = () => {
  updateTip({
    visible: false,
    ref: null,
  })
}

onMounted(() => {
  on(window, "click", closeTip)
})

onUnmounted(() => {
  off(window, "click", closeTip)
})

defineExpose({ closeTip })

// 列表配置
const dialogRef = ref()
const tableOptions = reactive({
  minHeight: 558,
  rowConfig: { height: 154 },
  headerConfig: { height: 42 },
  showOverflow: false,
  sortConfig: { remote: true, trigger: "cell", orders: ["desc", "asc", null] }, // 默认远程排序
  size: "small",
  id: "purchase-demand-intelligent" + type,
  customConfig: {
    storage: true,
    mode: "popup",
    allowFixed: false,
    immediate: false,
    visibleMethod: ({ column }) => {
      if (column.type || ["main_img", "sku", "sku_cn_title", "status"].includes(column.field) || !column.title) return false
      return true
    },
  },
  toolbarConfig: {
    custom: true,
  },
  formConfig: {
    save: props.sale ? "2" : "1",
    data: {
      type,
      input: { type: "sku", value: "" }, // 组合
      sku_sales_status: [],
      supply_status: [],
      activation: [],
      is_demand: [],
      replenishment_num: {},
      purchase_day: {},
      transit_day: {},
      safe_day: {},
      purchase_transit_num: {},
      headway_transit_num: {},
      oversea_usable_num: {},
      sale_week_num: {},
      sale_weeks_num: {},
      sort: {},
      dateRange: { type: "product_create_time", value: [], range: true },
    },
  },
  columns: [
    { type: "checkbox", fixed: "left", with: 40 },
    {
      title: "图片",
      field: "main_img",
      fixed: "left",
      minWidth: 120,
      slots: {
        default: ({ row }) => {
          return <VImage src={row.main_img} size="100px" preview-teleported />
        },
      },
    },
    {
      title: "产品信息",
      field: "sku",
      fixed: "left",
      minWidth: 180,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <VText title="SKU" value={row.sku} type="link" copy onClick={() => handleRow("sku", row)} />
              <VText title="SPU" value={row.spu} copy />
              <VText value="历史采购记录" type="button" onClick={() => historyRef?.value.open(row.sku, [row.country])} />
              <VText title="自定义SKU" value={row.custom_sku} title-position="top" />
              <VText title="国家" value={row.country_name} />
              {[2].includes(type) ? <VText title="仓库" value={row.warehouse_name} /> : ""}
              {[3].includes(type) ? <VText title="运营人员" value={row.sale_name} /> : ""}
            </div>
          )
        },
      },
    },
    {
      title: "状态",
      field: "status",
      fixed: "left",
      minWidth: 120,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <VText title="商品状态" value={row.sku_status_name} />
              <VText title="销售状态" value={row.sku_sale_status_name} />
              <VText title="活跃状态" value={row.activation_name} />
              <VText title="产品等级" value={row.product_level_name} />
            </div>
          )
        },
      },
    },
    {
      field: "sku_cn_title",
      title: "产品名称",
      fixed: "left",
      minWidth: 140,
      slots: {
        default: ({ row }) => <VText value={row.sku_cn_title} line={3} copy />,
      },
    },
    {
      field: "attribute_name",
      title: "产品分类属性信息",
      minWidth: 140,
      slots: {
        default: ({ row }) => <VText value={row.attribute_name} line={3} />,
      },
    },
    {
      field: "factory_remnant_num",
      title: "备料剩余数量",
      minWidth: 138,
      slots: {
        header: [{ title: "备料剩余数量", question: "SKU的备料计划的余料数之和", sort: "factory_remnant_num" }],
        default: ({ row }) => <VText value={row.factory_remnant_num} type="button" onClick={() => purchaseOrderRef?.value.open(row)} />,
      },
    },
    {
      field: "wait_order_num",
      title: "待下PO",
      minWidth: 106,
      slots: {
        header: [{ title: "待下PO", question: "审核通过的备库需求单的SKU待下单数量之和", sort: "wait_order_num" }],
        default: ({ row }) => <VText value={row.wait_order_num} type="button" onClick={() => dialogRef?.value.open(7, row)} />,
      },
    },
    {
      field: "purchase_transit_num",
      title: "采购在途",
      minWidth: 112,
      slots: {
        header: [{ title: "采购在途", question: "已下单还未收货的采购单的SKU的数量之和", sort: "purchase_transit_num" }],
        default: ({ row }) => <VText value={row.purchase_transit_num} type="button" onClick={() => dialogRef?.value.open(4, row)} />,
      },
    },
    {
      field: "local_usable_num",
      title: "本地仓可用",
      minWidth: 128,
      slots: {
        header: [{ title: "本地仓可用", question: "本地仓可以发货的库存", sort: "local_usable_num" }],
        default: ({ row }) => <VText value={row.local_usable_num} type="button" onClick={() => dialogRef?.value.open(1, row)} />,
      },
    },
    {
      field: "local_sendable_num",
      title: "本地仓待发",
      minWidth: 128,
      slots: {
        header: [{ title: "本地仓待发", question: "还没发货的头程备库单的SKU数量之和", sort: "local_sendable_num" }],
        default: ({ row }) => <VText value={row.local_sendable_num} type="button" onClick={() => dialogRef?.value.open([8], row, { is_send: 2 })} />,
      },
    },
    {
      field: "oversea_transit_num",
      title: "海外仓在途",
      minWidth: 128,
      slots: {
        header: [{ title: "海外仓在途", question: "头程在途的SKU数量之和", sort: "oversea_transit_num" }],
        default: ({ row }) => <VText value={`${row.oversea_transit_num} 头程记录`} type="button" onClick={() => dialogRef?.value.open([3, 6, 9], row)} />,
      },
    },
    {
      field: "oversea_usable_num",
      title: "海外仓可用",
      minWidth: 128,
      slots: {
        header: [{ title: "海外仓可用", question: "海外仓的可用库存数", sort: "oversea_usable_num" }],
        default: ({ row }) => <VText value={row.oversea_usable_num} type="button" onClick={() => dialogRef?.value.open(2, row)} />,
      },
    },
    {
      field: "oversea_balance_price",
      title: "海外仓结余金额",
      minWidth: 156,
      slots: {
        header: [{ title: "海外仓结余金额", question: "海外仓可用数*仓库的最新采购加权成本，多个加总", sort: "oversea_balance_price" }],
        default: ({ row }) => <VText value={row.oversea_balance_price} />,
      },
    },
    {
      field: "balance_num",
      title: "库存结余",
      minWidth: 100,
      slots: {
        header: () => (
          <div>
            库存结余
            <el-tooltip effect="dark" content="海外仓可用+海外仓在途+采购在途-未配货预出数" placement="top">
              <i class="dk-iconfont icon-QuestionFilled" />
            </el-tooltip>
          </div>
        ),
        default: ({ row }) => <VText value={row.balance_num} type="button" onClick={() => dialogRef?.value.open([2, 3, 4, 5], row, { str: "库存结余" })} />,
      },
    },
    {
      field: "balance_price",
      title: "库存结余金额",
      minWidth: 146,
      slots: {
        header: [{ title: "库存结余金额", question: "库存结余数*仓库的最新采购加权成本，多个加总", sort: "balance_price" }],
        default: ({ row }) => <VText value={row.balance_price} type="button" onClick={() => dialogRef?.value.open([2, 3, 9, 4, 5], row, { str: "库存结余金额" })} />,
      },
    },
    { visible: false, field: "sale_week_num", sortable: true },
    { visible: false, field: "sale_weeks_num", sortable: true },
    { visible: false, field: "sale_thirty_num", sortable: true },
    { visible: false, field: "sale_ninety_num", sortable: true },
    {
      field: "sale",
      title: "销量信息",
      minWidth: 140,
      slots: {
        header: () => (
          <div class="flex justify-between items-center">
            <span>销量信息</span>
            <VSort
              value={[
                { label: "一周销量", value: "sale_week_num" },
                { label: "两周销量", value: "sale_weeks_num" },
                { label: "30天销量", value: "sale_thirty_num" },
                { label: "90天销量", value: "sale_ninety_num" },
              ]}
              dropdown
            />
          </div>
        ),
        default: ({ row }) => {
          const { week_compare, month_compare } = row
          const config = {
            1: () => <i class="dk-iconfont icon-Upload text-[#67C23A] text-base" />,
            3: () => <i class="dk-iconfont icon-Minus text-[#E6A23C] text-base" />,
            2: () => <i class="dk-iconfont icon-Download text-[#F56C6C] text-base" />,
          }
          return (
            <div class="flex items-center justify-between gap-2">
              <div onMouseenter={(e) => handleMouseenter(row, e)} onMouseleave={(e) => closeTip(row, e)}>
                <VText title="一周" value={row.sale_week_num}>
                  <div class="text-green-600 font-bold">{row.sale_week_num}</div>
                </VText>
                <VText title="两周" value={row.sale_weeks_num}>
                  <div class="text-yellow-600 font-bold">{row.sale_weeks_num}</div>
                </VText>
                <VText title="30天" value={row.sale_thirty_num}>
                  <div class="text-red-600 font-bold">{row.sale_thirty_num}</div>
                </VText>
                <VText title="90天" value={row.sale_ninety_num}>
                  <div class="text-red-600 font-bold">{row.sale_ninety_num}</div>
                </VText>
                <el-button link type="primary" onClick={() => handleRow("sale", row)}>
                  <i class="dk-iconfont icon-Histogram" />
                </el-button>
              </div>
              <div class="flex flex-col gap-3">
                <VText title="周">{{ default: config[week_compare] }}</VText>
                <VText title="月">{{ default: config[month_compare] }}</VText>
              </div>
            </div>
          )
        },
      },
    },
    {
      field: "day",
      title: "库存可售天数",
      minWidth: 180,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <div class="font-bold">
                <VText title="总可售天数" value={row.total_sale_day} />
              </div>
              <VText title="采购在途">
                <el-button link type="primary">
                  {row.purchase_transit_saleable_day}天
                </el-button>
              </VText>
              <VText title="本地仓可用">
                <el-button link type="primary">
                  {row.local_usable_saleable_day}天
                </el-button>
              </VText>
              <VText title="本地仓待发">
                <el-button link type="primary">
                  {row.local_sendable_saleable_day}天
                </el-button>
              </VText>
              <VText title="海外仓可用">
                <el-button link type="primary">
                  {row.oversea_usable_saleable_day}天
                </el-button>
              </VText>
              <VText title="海外仓在途">
                <el-button link type="primary">
                  {row.oversea_transit_saleable_day}天
                </el-button>
              </VText>
            </div>
          )
        },
      },
    },
    { field: "safe_stock", title: "安全库存", minWidth: 80 },
    {
      field: "purchase_day",
      title: "供应LT",
      minWidth: 150,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <VText title="采购天数">{row.purchase_day}</VText>
              <VText title="运输天数">{row.transit_day}</VText>
              <VText title="安全天数">{row.safe_day}</VText>
              <VText title="中仓处理天数">{row.middle_process_day}</VText>
              <VText title="海外上架天数">{row.oversea_shelve_day}</VText>
              <VText title="采购频次">{row.purchase_frequency}</VText>
            </div>
          )
        },
      },
    },
    {
      field: "estimate_day_sale_num",
      minWidth: 150,
      slots: {
        header: [
          { title: "系统预估日均销量", sort: "estimate_day_sale_num" },
          { title: "运营预测日均销量", sort: "operate_estimate_day_sale_num" },
        ],
        default: ({ row, rowIndex }) => {
          return (
            <div>
              <VText title="系统" type="button" value={row.estimate_day_sale_num} onClick={() => handleRow("daySale", row)} />
              <VText title="运营" value={row.operate_estimate_day_sale_num} />
              <VText title="计划">
                <div class="w-full mb-1">
                  <el-input-number
                    v-model={row.plan_estimate_day_sale_num}
                    controls={false}
                    min={0}
                    size="small"
                    precision={0}
                    placeholder="请输入"
                    class="w-full"
                    onChange={() => handleRow("planSale", row, rowIndex)}
                  />
                </div>
              </VText>
              {row.sale_compare ? (
                <el-tag type={row.sale_compare === 3 ? "success" : "danger"} effect="dark">
                  {row.sale_compare_name}
                </el-tag>
              ) : (
                ""
              )}
            </div>
          )
        },
      },
    },
    {
      field: "week_compare",
      title: "销量对比",
      minWidth: 120,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <VText title="按周" value={row.week_compare_name} />
              <VText title="按月" value={row.month_compare_name} />
              <div>{row.estimate_sale_compare_name}</div>
            </div>
          )
        },
      },
    },
    {
      field: "user",
      title: "人员信息",
      minWidth: 160,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <VText title="计划专员" value={row.plan_user_name} />
              <VText title="采购专员" value={row.purchase_user_name} />
              <VText title="供应商专员" value={row.supplier_user_name} />
              <VText title="运营专员" value={row.operate_user_name} />
              <VText title="运营部门" value={row.operate_department_name} />
            </div>
          )
        },
      },
    },
    {
      field: "min_order_quantity",
      title: "采购信息",
      minWidth: 160,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <VText title="MOQ" value={row.min_order_quantity} />
              <VText title="MPQ" value={row.packing_qty} />
              <VText title="采购未税价" value={row.price_exclude_tax} />
              <VText title="供应商代码" value={row.supplier_code} />
            </div>
          )
        },
      },
    },
    {
      title: "运输类型/天数",
      minWidth: 140,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <VText title="类型" value={row.transport_type_name} />
              <VText title="运输天数" value={row.country_shipments} />
            </div>
          )
        },
      },
    },
    {
      field: "plan_num",
      title: "备料数量",
      minWidth: 140,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <div>{row.is_plan_name}</div>
              {row.plan_num}
              {/* <el-input-number v-model={row.plan_num} controls={false} min={0} step={1} precision={0} class="w-full mb-1" /> */}
              <div>备货{row.demand_day}天</div>
            </div>
          )
        },
      },
    },
    {
      field: "replenishment_num",
      title: "需求数量",
      minWidth: 140,
      slots: {
        default: ({ row, rowIndex }) => {
          return (
            <div>
              <div>{row.is_replenishment_name}</div>
              <el-input-number
                v-model={row.replenishment_num}
                v-loading={loadings["replenishment" + rowIndex]}
                controls={false}
                min={0}
                step={1}
                precision={0}
                class="w-full mb-1"
                onChange={() => handleRow("replenishment", row, rowIndex)}
              />
              <div>备货{row.demand_day}天</div>
              <el-text type={row.confirm_status_name === "未确认" ? "danger" : "success"}>{row.confirm_status_name}</el-text>
            </div>
          )
        },
      },
    },
    { field: "update_time", title: "更新时间", minWidth: 160 },
  ],
  proxyConfig: {
    autoLoad: false,
    ajax: {
      query: ({ page, form }) => api.query({ ...form, ...page }),
    },
  },
})
</script>

<style lang="scss">
.demand-intelligent-tip {
  width: 600px;
}
</style>
